import { ref, nextTick } from "vue";
import Taro from "@tarojs/taro";
import { useTzRouter } from "@/vhooks/useTzRouter";
export const useCcrnList = () => {
  //ccrn集合
  const ccrnList = ref([""]);

  const { navigateBack, route } = useTzRouter();
  //获取当前页面地址参数
  //通过页面地址参数显示是否编辑车辆信息
  if (route.query.ccrnInfo) {
    ccrnList.value = JSON.parse(route.query.ccrnInfo);
  }

  //校验
  const validteCcrn = (list) => {
    if (list.length === 0) {
      Taro.showToast({
        title: "请至少添加一个ccrn码!",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    for (const item of list) {
      if (item.length !== 10) {
        Taro.showToast({
          title: "ccrn码只能输入10位!",
          icon: "none",
          duration: 2000,
        });
        return false;
      }
    }
    return true;
  };

  //删除
  const delCcrn = (index) => {
    if (ccrnList.value.length === 1) {
      ccrnList.value[0] = "";
    } else {
      ccrnList.value.splice(index, 1);
    }
  };
  //添加
  const addCcrn = () => {
    if (ccrnList.value.length >= 50) {
      Taro.showToast({
        title: "ccrn最多只能录入50个!",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    ccrnList.value.push("");
  };
  //保存
  const saveClick = () => {
    //过滤掉为空的数据
    const filterCcrnList = ccrnList.value.filter((item) => item);
    console.log(filterCcrnList);
    if (!validteCcrn(filterCcrnList)) {
      return false;
    }
    navigateBack({
      delta: 1,
      event: {
        type: "ccrnBack", //事件类型 ，可以自己任意定义
        data: filterCcrnList, //回退的数据
      },
    });
  };
  return () => (
    <>
      <tz-view class="section">
        <tz-cell title="录入CCRN" border class="text-right">
          <tz-button type="primary" size="small" onClick={addCcrn}>
            添加CCRN
          </tz-button>
        </tz-cell>
        {ccrnList.value.map((item, index) => (
          <tz-cell title={index + 1 + "-CCRN->"} key={index} border class="fix">
            <tz-input
              v-model={ccrnList.value[index]}
              type="number"
              placeholder="请输入CCRN号"
              maxlength="10"
              rules={(val) => {
                return val && val.replace(/[^\d]/g, "");
              }}
            />
            <tz-icon name="close" onClick={() => delCcrn(index)}></tz-icon>
          </tz-cell>
        ))}
      </tz-view>
      <tz-button class="save-btn" type="primary" onClick={saveClick}>
        保存
      </tz-button>
    </>
  );
};
